import {View, ScrollView, Text, Image, Button} from '@tarojs/components';
import Taro from '@tarojs/taro';
import React from 'react';
import {connect} from 'react-redux';
import * as T from './types';
import './index.less';
import actions from './actions';
import {STATUS_DOWN, GAME_TYPE_ZHUAWAWA} from './constant';
import {store2Props} from './selectors';
import Bottom from './components/bottom/index';
import testImg from '@/assets/image/ipland/test.png';
import rightIcon from '@/assets/image/ipland/t_right.png';
import icon2 from '@/assets/image/ipland/icon2.png';
import notdata from '@/assets/image/ipland/notdata.png';
import CustomScrollView from '@/common/scrollview';

//@ts-ignore
actions().actions.loadReducer();
//@ts-ignore
@connect<Partial<T.IProps>, any>(store2Props, actions)
export default class WishingPool extends React.Component<Partial<T.IProps>, any> {
  constructor(props) {
    super(props);
    this.state = {
      refresherTriggered: false,
    };
  }

  componentWillUnmount() {
    this.props.actions.clean();
  }

  componentWillMount(): void {
    this.props.actions.init();
  }

  componentDidShow() {
    this.handleQueryWishItems({});
    this.handleQueryRecommendItems();
  }

  componentWillReceiveProps(nextProps: Readonly<Partial<T.IProps>>, nextContext: any): void {
    if (nextProps.main.status.loadingWish == false && this.props.main.status.loadingWish == true) {
      console.log('查询结束了哦');
      this.setState({
        refresherTriggered: false,
      });
    }

    if (nextProps.main.status.removeingWish == false && this.props.main.status.removeingWish == true) {
      Taro.showToast({
        title: nextProps.main.codeMessage || '清空成功',
        icon: 'none',
        duration: 2000,
      });

      // 重新查询数据
      this.handleQueryWishItems({
        pageNum: 0,
      });
    }
  }

  /**
   * 查询许愿列表
   */
  handleQueryWishItems = (pagation) => {
    const {
      main: {page},
    } = this.props;
    let params = {
      ...page,
      ...pagation,
    };
    console.log('index.tsx handleQueryWishItems params', params);
    this.props.actions.action.loadWishItemsByPage(params);
  };

  /**
   * 推荐商品查询
   */
  handleQueryRecommendItems = () => {
    let params = {};
    this.props.actions.action.fetchrecommendation();
  };

  /**
   * 拉倒底部
   */
  handleScrollLower = async () => {
    console.log('index.tsx handleScrollLower ');
    const {
      main: {page, wishItems},
    } = this.props;
    let params = {
      ...page,
      pageNum: page.pageNum + 1,
    };
    if (params.pageNum > 0 && wishItems.length == page.total) {
      return;
    }
    this.handleQueryWishItems(params);
  };

  /**
   * 下拉刷新（重置）
   * @returns
   */
  handleRreshList = () => {
    const {
      main: {
        page: {pageSize},
      },
    } = this.props;
    let {refresherTriggered} = this.state;
    if (refresherTriggered) return;
    this.setState({
      refresherTriggered: true,
    });

    // 查询列表
    this.handleQueryWishItems({
      pageSize,
      pageNum: 0,
      total: 0,
    });
  };
  render() {
    let {refresherTriggered} = this.state;
    let {
      main: {wishItems},
    } = this.props;
    return (
      <CustomScrollView
        className="packageIWishingPool"
        scrollY
        onScrollToLower={this.handleScrollLower}
        refresherEnabled
        refresherTriggered={refresherTriggered}
        onRefresherRefresh={this.handleRreshList}
      >
        {wishItems.length > 0 ? (
          <View className="wishPoolBox">
            <View className="topFirst">
              <Text className="title">我的许愿池</Text>
              <Text className="emptyText" onClick={this.handleClearInvalidWish}>
                清空失效
              </Text>
            </View>
            <View className="wishBox">
              {wishItems.map((i: any, index: number) => (
                <View className="wishBox-item" key={'wish' + index}>
                  <Image className="wishBox-item-img" src={i.goodsInfoImg} mode="aspectFill" />
                  <View className="wishBox-item-con">
                    <Text className="wishBox-item-con-name">{i.goodsInfoName}</Text>
                    {i.status == STATUS_DOWN ? <Image className="removedIcon" src={icon2} mode="heightFix" /> : <></>}
                    <View className="wishBox-item-con-getBox" onClick={() => this.handleGamePlay(i)}>
                      <Text>去获取</Text>
                      <Image className="rightIcon" src={rightIcon} mode="widthFix" />
                    </View>
                  </View>
                </View>
              ))}
            </View>
          </View>
        ) : (
          <View className="notdataBox">
            <View className="notdataCon">
              <Image className="notdatabg" src={notdata} mode="widthFix" />
              <Text className="notdataText">许愿池空空，快去游戏中许愿吧~</Text>
              {/* <View onClick={()=> {
                Taro.navigateTo({
                  url: '/pages/package-I/home/index'
                })
               }} className='notdataLabel'>{`去看看 >>`}</View> */}
            </View>
          </View>
        )}
        <Bottom />
      </CustomScrollView>
    );
  }

  /**
   * 清除无效的心愿信息
   */
  handleClearInvalidWish = () => {
    console.log('index.tsx handleClearInvalidWish 清除无效的心愿信息');
    let _this = this;
    Taro.showModal({
      title: '提示',
      content: '您是否确认清除失效的商品？',
      success: function (res) {
        if (res.confirm) {
          console.log('BUGXX this.prosp', this.props);
          _this.props.actions.action.removeWish({});
        }
      },
    });
  };

  /**
   * 跳转到游戏
   */
  handleGamePlay = (item) => {
    console.log('index.tsx wishingPool handleGamePlay item', item);

    // 如果是抓娃娃就跳转到游戏
    if (item.gameType == GAME_TYPE_ZHUAWAWA) {
      Taro.navigateTo({
        url: '/pages/package-I/home/index',
      });
    } else {
      Taro.showToast({
        title: '游戏暂无开启，敬请期待',
        icon: 'none',
        duration: 2000,
      });
    }
  };
}

//create by moon https://github.com/creasy2010/moon
